<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head> 
    <%@ include file="/include/tasklibs.jsp" %>
    <style>
        .fixed-table-body thead th .th-inner {
            text-align: center;
        }
 
        .shotline {
            border-bottom: solid 2px #B4B4B4;
        }

        .textAlign-right {
            text-align: right;
        }

        #storeInfoTableContainer {
            display: none;
            padding: 10px;
        }

        .btn-default {
            background-color: #2F4050;
        }

        .dz-success-mark {
            display: none;
        }

        .dz-error-mark {
            display: none;
        }

        .dz-error-message {
            display: none;
        }

        .bv-form .help-block {
            margin-bottom: 0;
        }

        .bv-form .tooltip-inner {
            text-align: left;
        }

        .nav-tabs li.bv-tab-success > a {
            color: #3c763d;
        }

        .nav-tabs li.bv-tab-error > a {
            color: #a94442;
        }

        .bv-form .bv-icon-no-label {
            top: 0;
        }

        .bv-form .bv-icon-input-group {
            top: 0;
            z-index: 100;
        }
    </style>

    <script type="text/javascript">
       function fucCheckLength(strTemp) {
    	   if(null !=strTemp && ""!=strTemp){
    		   return strTemp.length;
    	   }else {
    		   return 0;
    	   }
    	  return strTemp.length; 
    	}
        $(function () {
            $('form').bootstrapValidator({
                feedbackIcons: {
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                excluded:[":disabled"],
                fields: {
                    taskName: {
                        validators: {
                            notEmpty: {
                                message: '任务名称不能为空'
                            },
                            callback: {
                                message: '字数不能超过30',
                                callback: function (value, validator, $field) {
                                    var m=fucCheckLength(value);
                                    return m<31;
                                }
                            }
                        }
                    },
                    startTime: {
                        validators: {
                            notEmpty: {
                                message: '开始时间不能为空'
                            },
                            callback: {
                                message: '开始日期不能大于结束日期',
                                callback: function (value, validator, $field) {
                                    var begin = $('#startDate').val();
                                    var end = $('#endDate').val();
                                    $('#startDate').keypress();
                                    $('#endDate').keypress();
                                    console.log(begin);
                                    console.log(end);
                                    return begin <= end;
                                }
                            }
                        }
                    },
                    endTime: {
                        validators: {
                            notEmpty: {
                                message: '结束时间不能为空'
                            },
                            callback: {
                                message: '结束日期不能小于开始日期',
                                callback: function (value, validator, $field) {
                                    var begin = $('#startDate').val();
                                    var end = $('#endDate').val();
                                    $('#startDate').keypress();
                                    $('#endDate').keypress();
                                    console.log(parseInt(end));
                                    console.log(parseInt(begin))
                                    console.log(begin > end);
                                    return end >= begin;
                                }
                            }
                        }
                    },
                    reward: {
                    	    validators: {
                            callback: {
                                message: '只能输入数字,且小数点后最多两位！',
                                callback: function (value, validator, $field) {
                                	if(value.length>0 ){
                                      var reg = /^([1-9]\d*|0)(\.\d{1,2})?$/;
                                      return parseFloat(value) > 0 && reg.test(value);
                                	}else {
                                		return true;
                                	}
                                }
                            }
                        }
                    },
                    storeCode: {
                        validators: {
                            notEmpty: {
                                message: '任务地点不能为空'
                            }
                        }
                    },
                    taskGuidancePicture:{
                    	 validators: {
                    		 callback: {
                    	          message: '图片只能上传5个,请删除多余的图片',
                    	          callback:function(value, validator,$field,options){
                    	            var begin = $('#taskDropzone').attr("value");
                    	            console.log(begin);
                    	            if(null ==begin|| ""==begin){
                    	            	return true;
                    	            }else {
                    	            	return parseInt(begin)<6;
                    	            }
                    	          }
                    	        }
                         }
                    },
                    taskRequire:{
                    	 validators: {
                    		 callback: {
                    	          message: '字符内容长度不能超过500',
                    	          callback:function(value, validator,$field,options){
                    	        	  var m=fucCheckLength(value);
                    	        	  console.log(m)
                                      return m<501;
                    	          }
                    	        }
                         }
                    },
                    taskGuidanceWords:{
                    	 validators: {
                    		 callback: {
                    	          message: '字符内容长度不能超过500',
                    	          callback:function(value, validator,$field,options){
                    	        	  var m=fucCheckLength(value);
                    	        	  console.log(m)
                                      return m<501;
                    	          }
                    	        }
                         }
                    }
                }
            });
        }); 

        function changeVal(type) {
            if (type == 1) {
                setTimeout("val(1)", 200);
            } else {
                setTimeout("val(2)", 200);
            }
        }

        function val(type) {
            var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
            if (type == 1) {
                bootstrapValidator.updateStatus('endTime', 'NOT_VALIDATED').validateField('endTime');
                bootstrapValidator.updateStatus('startTime', 'NOT_VALIDATED').validateField('startTime');
            } else {
                var storeCode = "";
                $("#taskList  tr td:nth-child(4)").each(function (j, el) {
                    console.log($(this).html());
                    if ("" == storeCode) {
                        storeCode = $(this).html()
                    } else {
                        storeCode = $(this).html() + "," + storeCode;
                    }
                });
                console.log(storeCode);
                $("#storeCode").val(storeCode);
                bootstrapValidator.updateStatus('storeCode', 'NOT_VALIDATED').validateField('storeCode');
            }
        }
        function saveReport() { 
        	 var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
        	 var status = $("#status").val();
        	 bootstrapValidator.validate();
             if(!bootstrapValidator.isValid()){  
                 return false;  
             }
        	// jquery 表单提交 
        	$.ajax({ type: "POST",
        		     url:"web/saveParentTask.json",
        		     data:$('#taskForm').serialize() , success: function(data){
        		    	 if(data.result==1){
        		    	   bootstrapValidator.updateStatus('storeCode', 'VALID').validateField('storeCode');
        		    	   $("#taskid").val(data.msg);
        		    	   if(status=='SAVE'){
        		    	   layer.msg("保存成功");
        		    		   return false;   
        		    	   }else{
        		    	   layer.msg("发布成功");   
        		    		   $('.J_iframe').load('web/taskList.html');  
        		    	   }
        		    	 }else{
        		    		 layer.msg(data.msg);
        		    		 return false;
        		    	 }
        		     }, error: function(data) {
//        		    	 layer.msg("操作失败");
        		    	 return false;
                     }});
        	   return false; // 必须返回false，否则表单会自己再做一次提交操作，并且页面跳转 
        	} 
    </script>
</head>
<div class="animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <form method="post" class="form-horizontal" action="<c:url value="/web/saveParentTask.json" />" id="taskForm" onsubmit = "return saveReport();" >
                        <input type="hidden" id="status" name="status" value="SAVE">
                        <input type="hidden" id="imageUrl" name="taskGuidancePictures">
                        <input type="hidden" name="id" id="taskid" >
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务类型</label>

                            <div class="col-sm-8">
                                <label class="radio-inline i-checks" id="radio">
                                    <input type="radio" value="DATA" checked name="taskType" id="firt">数据采集</label>
                                <label class="radio-inline i-checks">
                                    <input type="radio" value="INVEST" name="taskType">市调</label>
                                <label class="radio-inline i-checks">
                                    <input type="radio" value="ARRANG" name="taskType">理贷</label>
                                <label class="radio-inline i-checks">
                                    <input type="radio" value="PROMOTION" name="taskType">促销</label>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务名称</label>

                            <div class="col-sm-8">
                                <input type="text" placeholder="请输入任务名称" id="taskName" name="taskName"
                                       class="form-control">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务周期</label>

                            <div class="col-sm-8">
                                <input id="startDate" class="laydate-icon form-control layer-date" name="startTime"
                                       onblur="changeVal(1)" autocomplete="off">
                                <span class="shotline">&emsp;&emsp;&emsp;</span>
                                <input id="endDate" class="laydate-icon form-control layer-date" name="endTime"
                                       onblur="changeVal(1)" autocomplete="off">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务赏金</label>

                            <div class="col-sm-4">
                                <div class="input-group m-b"><span class="input-group-addon">&yen;</span>
                                    <input type="text" placeholder="" class="form-control" name="reward">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务地点</label>

                            <div class="col-sm-4">
                                <button class="btn btn-default" type="button" id="addAddressBtn" onblur="changeVal(2)">
                                    <i class="fa fa-plus"></i>&nbsp;&nbsp;添加地点
                                </button>
                                <button class="btn btn-default " type="button" id="excelDropzone"
                                        onmousedown="changeData()" onblur="changeVal(2)">
                                    <i class="fa fa-upload"></i>&nbsp;&nbsp;导入Excel
                                 <input style="height:0.05px;width:0px;padding:0px;margin:0px;" id="storeCode"
                                       name="storeCode">
                                </button>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务要求</label>

                            <div class="col-sm-8">
                                <textarea id="requireEditor" placeholder="请输入任务要求" autofocus name="taskRequire">

                                </textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务指引</label>

                            <div class="col-sm-8">
                                <textarea id="guideEditor" placeholder="请输入任务指引" autofocus name="taskGuidanceWords">

                                </textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">附件上传</label>

                            <div class="col-sm-8">
                                <div id="taskDropzone" style="min-height: 250px;" class="dropzone"
                                     name="taskGuidancePicture" value="0">
                                     </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-3 col-sm-offset-5">
                                <button class="btn btn-default" type="button" id="publisParentTaskBtn"
                                        onmousedown="changeStatus(1)" onclick="saveReport()">发布
                                </button>
                            </div>
                            <div class="col-sm-4">
                                <button class="btn btn-default" type="button" id="submitParentTaskBtn"
                                        onmousedown="changeStatus(0)" onclick="saveReport()">保存
                                </button>
                                <button class="btn btn-default" type="reset" id="refresh" >取消
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div id="toolbar">
                    <button id="buttonRemove" class="btn btn-default">删除子任务</button>
                </div>
                <div class="ibox-content">
                    <table id="taskList"></table>
                </div>
            </div>
        </div>
    </div>
    <!--选择门店信息表格-->
    <div id="storeInfoTableContainer">
        <table id="storeInfoTable"></table>
    </div>
</div>

<script>
var taskName = "";
var startDate = "";
var endDate = "";
var $table = $('#taskList');
var $button = $('#buttonRemove');
var $refresh = $("#refresh");
var bootstrapValidator = $("#taskForm").data('bootstrapValidator');

$(function () {
    $button.click(function () {
        var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
            return row.id;
        });
        $table.bootstrapTable('remove', {
            field: 'id',
            values: ids
        });
        var storeCode = "";
        $("#taskList  tr td:nth-child(4)").each(function (j, el) {
            if ("" == storeCode) {
                storeCode = $(this).html()
            } else {
                storeCode = $(this).html() + "," + storeCode;
            }
        });
        $("#storeCode").val(storeCode);
        var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
        bootstrapValidator.updateStatus('storeCode', 'NOT_VALIDATED').validateField('storeCode');
    });
    $refresh.click(function () {
    	
    	$("input[name='taskType'][value=DATA]").attr("checked",true); 
    	$(".iradio_square-green").removeClass("checked");
    	$(".iradio_square-green").first().addClass("checked");
    	$(".dz-preview").remove();
        $table.bootstrapTable('removeAll');
        $('.J_iframe').load("web/taskPublish.html");
    });
});
function changeData() {
    taskName = $("#taskName").val();
    startDate = $("#startDate").val();
    endDate = $("#endDate").val();
}
function changeStatus(val) {
    if (val == 0) {
        $("#status").val("SAVE");
    } else {
        $("#status").val("PUBLISH");
        //$("#taskForm").removeAttr("onsubmit");
    }
    var storeCode = "";
    $("#taskList  tr td:nth-child(4)").each(function (j, el) {
        if ("" == storeCode) {
            storeCode = $(this).html()
        } else {
            storeCode = $(this).html() + "," + storeCode;
        }
    });
    $("#storeCode").val(storeCode);
}
function removeFile(fileName){
	var source = $("#imageUrl").val();
	var strs= new Array(); 
	var result= new Array(); 
	strs=source.split(",");
    var imageUrl = null;
	for (i=0;i<strs.length ;i++ ) 
	{ 
		 if(strs[i].indexOf(fileName)>0){
			   console.log("删除他")}
		 else {
           if (imageUrl != null && imageUrl != "") {
               imageUrl = imageUrl + "," +strs[i]
           } else {
               imageUrl = strs[i];
           }
	   }
	} 
	$("#imageUrl").val(imageUrl);
	console.log(fileName +"--------------------")
	$(this).remove();
	  
}
var Controller = {
    taskListTable: null,
    storeInfoTable: null,
    init: function () {
        Controller.initLaydate();
        Controller.initEditor();
        Controller.initDropzone();
        Controller.initTable();
    },
    initLaydate: function () {
        laydate({
            elem: '#startDate'
        });
        laydate({
            elem: '#endDate'
        });
    },
    initDropzone: function () {
        var goUrl = "web/taskExcelUpload.json?" + "taskName=" + taskName + "&startDate=" + startDate + "&endDate" + endDate
        $("#excelDropzone").dropzone({ url: goUrl, 
        	acceptedFiles: ".xls,.xlsx", 
        	addRemoveLinks: true,
        	maxFiles:5,
            init: function () {
                this.on("success", function (files, response) {
                    if (response.result) {
                        console.log(response.rows);
                        var json = response.rows;
                        console.log(json)
                        
                        $(json).each(function (i, ele) {
                            var next = 0;
                            $("#taskList  tr td:nth-child(4)").each(function (j, el) {
                                if (ele.storeCode == $(this).html()) {
                                    next = 1;
                                    return false;
                                }
                            });
                            if (next == 1 || ele.storeCode == null || ele.storeCode == "") {
                                return true;
                            }
                            console.log(ele.storeCode);
                            Controller.taskListTable.bootstrapTable('insertRow', {
                                index: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                row: {
                                    id: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                    storeCode: ele.storeCode,
                                    taskName: $('#taskName').val(),
                                    storeName: ele.storeName,
                                    storeAddress: ele.storeAddress,
                                    startDate: $('#startDate').val(),
                                    endDate: $('#endDate').val()
                                }
                            });
                        });
                        if(null != response.msg && "" !=response.msg) {
                        	layer.alert(response.msg); 
                        }
                    }
                });
            } });
 
        $("#taskDropzone").dropzone({ url: "web/taskImageUpload.json", acceptedFiles: "image/*", addRemoveLinks: true, maxFiles: 5,
            init: function () {
                this.on("success", function (files, response) {
                    var imageUrl = $("#imageUrl").val();
                    if (imageUrl != null && imageUrl != "") {
                        imageUrl = imageUrl + "," + response.msg
                    } else {
                        imageUrl = response.msg;
                    }
                    $("#imageUrl").val(imageUrl);
                    var bvbootstrapValidator = $("#taskForm").data('bootstrapValidator');
                    if($("div").hasClass("dz-error")){
                    	$("#taskDropzone").attr("value","6"); 
                    	bvbootstrapValidator.updateStatus('taskGuidancePicture', 'INVALID').validateField('taskGuidancePicture');
                    }else{
                	   bvbootstrapValidator.updateStatus('taskGuidancePicture', 'NOT_VALIDATED').validateField('taskGuidancePicture');
                    }
                });
                this.on("removedfile", function (file) {
                	var bvbootstrapValidator = $("#taskForm").data('bootstrapValidator');
                	if($("div").hasClass("dz-error")){
                    	$("#taskDropzone").attr("value","6").change();
                	bvbootstrapValidator.updateStatus('taskGuidancePicture', 'INVALID').validateField('taskGuidancePicture');
                    }else{
                    	$("#taskDropzone").attr("value","0");
                	bvbootstrapValidator.updateStatus('taskGuidancePicture', 'NOT_VALIDATED').validateField('taskGuidancePicture');
                    }
                    removeFile(file.name);
                });
                this.on("maxfilesreached", function (file) {
                	var bvbootstrapValidator = $("#taskForm").data('bootstrapValidator');
                 
                	bvbootstrapValidator.updateStatus('taskGuidancePicture', 'INVALID').validateField('taskGuidancePicture');
                }); 
            } });
    },
    initTable: function () {
        Controller.taskListTable = $('#taskList').bootstrapTable({
            columns: [
                {
                    field: 'id',
                    title: '序号',
                    width: '40px',
                    checkbox: true,
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    field: 'code',
                    title: '任务编码'
                },
                {
                    field: 'taskName',
                    title: '任务名称'
                },
                {
                    field: 'storeCode',
                    title: '门店编码'
                },
                {
                    field: 'storeName',
                    title: '门店名称'
                },
                {
                    field: 'storeAddress',
                    title: '门店地址'
                },
                {
                    field: 'startDate',
                    title: '开始日期'
                },
                {
                    field: 'endDate',
                    title: '结束日期'
                }
            ], 
            pagination: true,
            pageSize: 1000,
            sidePagination: 'client',
            pageNumber: 1,
            pageList: [],
            idField: 'id', //主键
            uniqueId: 'id'
        });
        Controller.storeInfoTable = $('#storeInfoTable').bootstrapTable({
            url: 'web/getAllStore.json',
            columns: [
                {
                    checkbox: true,
                    field: 'checkbox'
                },
                {
                    field: 'storeCode',
                    title: '门店编码'
                },
                {
                    field: 'storeName',
                    title: '门店名称'
                },
                {
                    field: 'storeAddress',
                    title: '门店地址'
                }
            ],
            search: true,
            checkboxHeader: true,
            sidePagination: 'client',
        });
    },
    initEditor: function () {
        var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
        var requireEditor = new Simditor({
            textarea: $('#requireEditor')
        });
        requireEditor.on("blur",(function(){
        	 bootstrapValidator.updateStatus('taskRequire', 'NOT_VALIDATED').validateField('taskRequire');
        	 
        })) 
        var guideEditor = new Simditor({
            textarea: $('#guideEditor')
        });
        guideEditor.on("blur",(function(){
       	 bootstrapValidator.updateStatus('taskGuidanceWords', 'NOT_VALIDATED').validateField('taskGuidanceWords');
       })) 
    },
    bindEvents: function () {

        $('#addAddressBtn').click(function () {
        	$('#storeInfoTable').bootstrapTable("resetSearch");
            // 弹出框
            layer.open({
                type: 1,
                title: '选择门店',
                content: $('#storeInfoTableContainer'), // 只要是DOM就会出现CSS显示错误？？？？
                success: function(layero, index){
						// 只要是DOM就会出现CSS显示错误解决方法
						$('#layui-layer1').appendTo('.J_iframe');
					},
                area: ['800px', '500px'],
                zIndex: 1000,
                shade: false,
                btn: ['确认添加'],
                btn1: function () {
                    // 勾选的门店信息添加到最下面的表格中
                    var checkedData = Controller.storeInfoTable.bootstrapTable('getSelections');
                    var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
                    if (checkedData.length > 0) {
                    	var code = "";
                        $(checkedData).each(function (i, ele) {
                            var next = 0;
                            $("#taskList  tr td:nth-child(4)").each(function (j, el) {
                                if (ele.storeCode == $(this).html()) {
                                    next = 1;
                                    return false;
                                }
                            });
                            if (next == 1) {
                                return true;
                            }
                            if (next == 1 || ele.storeCode == null || ele.storeCode == "") {
                                return true;
                            }
                            console.log("----------------------------------" + ele.storeCode);
                            if("" ==code){
                            	code = ele.storeCode +"," ;
                            }else {
                            	code = code + ele.storeCode +"," ;
                            }
                            $table.bootstrapTable('insertRow', {
                                index: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                row: {
                                    id: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                    storeCode: ele.storeCode,
                                    taskName: $('#taskName').val(),
                                    storeName: ele.storeName,
                                    storeAddress: ele.storeAddress,
                                    startDate: $('#startDate').val(),
                                    endDate: $('#endDate').val()
                                }
                            });
                        });
                        $("#storeCode").val(code);
                        bootstrapValidator.updateStatus('storeCode', 'NOT_VALIDATED').validateField('storeCode');
                    }
                    

                }
            });
        });
    }
}

$(document).ready(function () {
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
    Controller.init();
    Controller.bindEvents();
});

</script>

